import akshare as ak
import pandas


# 指数相似度
class IndexSimilarity:
    def __init__(self, code, name):
        self.code = code
        self.name = name

indexList = []
indexList.append(IndexSimilarity("000300", '中证中药指数'))
indexList.append(IndexSimilarity("399300", '中证生物科技主题指数'))
indexStockList = []
for e in indexList:
    # 获取指数成份股信息
    df = ak.index_stock_cons(symbol=e.code)
    print(df)
    indexStockList.append(df['品种代码'].tolist())

df = ak.index_stock_cons(symbol='000300')
df.to_excel('沪深300指数成分股.xlsx')

for i, e in enumerate(indexStockList):
    if i == len(indexStockList) - 1:
        break
    sortedI = sorted(e)
    sortedIx = sorted(indexStockList[i + 1])
    total = len(e) + len(indexStockList[i + 1])
    comm = 0
    commList = []
    for stock_1 in e:
        for stock_2 in indexStockList[i + 1]:
            if stock_1 == stock_2:
                comm += 2
                commList.append(stock_1)
                break

    # 求相似度
    simaler = round(comm * 100 / total, 2)
    print(simaler)
    print(commList)
